package com.loctek.importexport.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;


import com.gyf.barlibrary.ImmersionBar;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.loctek.importexport.App;
import com.loctek.importexport.Constants;
import com.loctek.importexport.R;
import com.loctek.importexport.mosby3.mvp.MvpActivity;
import com.loctek.importexport.mosby3.mvp.MvpPresenter;
import com.loctek.importexport.mosby3.mvp.MvpView;
import com.loctek.importexport.util.MenuColorizer;
import com.loctek.importexport.util.ToastUtils;
import com.squareup.picasso.Picasso;
import com.trello.rxlifecycle.LifecycleTransformer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃  神兽保佑
 * 　　　　┃　　　┃  代码无bug
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 * <p>
 * 作者：司海林
 * 邮箱：sihailin@sina.cn
 * 时间：2017/9/7
 * 描述：
 */

public abstract class BaseActivity<V extends MvpView, P extends MvpPresenter<V>> extends MvpActivity<V, P> {


    private boolean isSpecialActionbar;

    private ProgressBar mProgressBar;


    protected ImmersionBar mImmersionBar;

    private boolean isOverlayActionBar;

    /**
     * 绑定布局文件
     *
     * @return 布局文件ID
     */
    @LayoutRes
    protected abstract int attachLayoutRes();

    /**
     * Dagger 注入
     */
    protected abstract void initInjector();

    /**
     * 初始化视图控件
     */
    protected abstract void initViews();

    /**
     * 更新视图控件
     */
    protected abstract void updateViews(boolean isRefresh);

//    protected ImmersionBar mImmersionBar;

    public KProgressHUD progressHUD;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewBefore();
        super.setContentView(isOverlayActionBar ? R.layout.toolbar_acitvity_overlay_holder : R.layout.toolbar_acitvity_holder);

        if (!showToolbar()) {
            //有些界面不需要Toolbar
            View toolbar_ll = findViewById(R.id.toolbar_ll);
            toolbar_ll.setVisibility(View.GONE);
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (isSpecialActionbar) {
            mProgressBar = (ProgressBar) findViewById(R.id.progress_spinner);
        }
        setUpToolBar();


        progressHUD = KProgressHUD.create(BaseActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(getResources().getString(R.string.tip_is_loading))
                .setDetailsLabel(getResources().getString(R.string.moment_please))
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f);
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.fitsSystemWindows(true).statusBarDarkFont(true, 0.2f).init();   //所有子类都将继承这些相同的属性


        setContentView(attachLayoutRes());
        ButterKnife.bind(this);

        initInjector();

        initViews();
        updateViews(false);

        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_INTENT_OUT_LOGIN);
        registerReceiver(receiver, filter);


    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), Constants.ACTION_INTENT_OUT_LOGIN)) {
                finish();
            }
        }
    };

    private void setUpToolBar() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
    }


    public void showLoading() {
        if (!progressHUD.isShowing()) {
            progressHUD.show();
        }
    }

    public void dismissLoading() {
        if (progressHUD.isShowing()) {
            progressHUD.dismiss();
        }
    }

    /**
     * 设置view 之前 ， 如全屏操作
     */
    protected void setContentViewBefore() {

    }

    protected boolean showToolbar() {
        return true;
    }


    @Override
    public void setContentView(int layoutResID) {
        ((FrameLayout) findViewById(R.id.view_holder)).removeAllViews();
        LayoutInflater.from(this).inflate(layoutResID, (FrameLayout) findViewById(R.id.view_holder));

    }

    @Override
    public void setContentView(View view) {
        ((FrameLayout) findViewById(R.id.view_holder)).removeAllViews();
        ((FrameLayout) findViewById(R.id.view_holder)).addView(view);
    }


    public void setProgressVisible(boolean visible) {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(visible ? View.VISIBLE : View.GONE);
        } else {
            if (visible) {
                throw new IllegalArgumentException("may not execute enableProgress() ");
            } else {
                View view = findViewById(R.id.progress_spinner);
                if (view != null) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoading();
        unregisterReceiver(receiver);
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //需要在activtiy中创建menu
        MenuColorizer.colorMenu(this, menu, R.color.theme_main_color);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 设置分割线是否显示,需要全屏显示的时候需要设置,否则会有白边
     *
     * @param visible
     */
    protected void setDivideLineVisible(boolean visible) {
        View divideNormal = findViewById(R.id.toolbar_divide_line_normal);
        if (divideNormal != null) {
            divideNormal.setVisibility(visible ? View.VISIBLE : View.GONE);
        }
        View divideDark = findViewById(R.id.toolbar_divide_line_dark);
        if (divideDark != null) {
            divideDark.setVisibility(visible ? View.VISIBLE : View.GONE);
        }
    }

    protected void setBackgroundColor(int colorRes) {
        View view = findViewById(R.id.base_toolbar_activity_holder);
        if (view != null) {
            view.setBackgroundResource(colorRes);
        }
    }


    public void showProgress() {
        showLoading();
    }

    public void onCompleted() {
        dismissLoading();
    }

    public void onError(Throwable e) {
        dismissLoading();
        ToastUtils.showToast(getResources().getString(R.string.connection_timeout));
    }

    public void showMsg(String msg) {
        dismissLoading();
        ToastUtils.showToast(msg);
    }

    public void navToLogin() {
        getApp().logout();
    }


    public void LoadingImg(ImageView img, int targetWidth, int targetHeight, String url) {
        Picasso.with(getApp()).load(url).resize(targetWidth, targetHeight).centerCrop().error(R.color.color_f_2).into(img);
    }

    public void LoadingImg(ImageView img, int targetWidth, int targetHeight, File file) {
        Picasso.with(getApp()).load(file).resize(targetWidth, targetHeight).centerCrop().into(img);
    }

    public void LoadingImg(ImageView img, int targetWidth, int targetHeight, int reId) {
        Picasso.with(getApp()).load(reId).resize(targetWidth, targetHeight).centerCrop().into(img);
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    public App getApp() {
        return (App) getApplication();
    }


    public static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }

}
